/*
 * Copyright 2011 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fr.gaellalire.jzip.view;

import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker.StateValue;

import fr.gaellalire.jzip.actions.AbstractCompressAction;
import fr.gaellalire.jzip.actions.BasicCompressAction;
import fr.gaellalire.jzip.actions.FileListCompressAction;
import fr.gaellalire.jzip.actions.FutureEntry;

/**
 *
 * @author Gael Lalire
 */
public final class JZipActivitiesFrame extends JPanel implements PropertyChangeListener {

    private static final long serialVersionUID = -6707165381146553249L;

    private static final JZipActivitiesFrame INSTANCE = new JZipActivitiesFrame();

    private static JFrame frame;

    private AbstractCompressAction task;

    static {
        frame = new JFrame("Activités");
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

        // Create and set up the content pane.
        INSTANCE.setOpaque(true); // content panes must be opaque
        frame.setContentPane(INSTANCE);

        // Display the window.
        frame.pack();
    }

    public static Future<Void> compressTo(final List<FutureEntry> futureEntries, final OutputStream result, final Runnable runnable) {
        BasicCompressAction task = new BasicCompressAction(result, futureEntries) {
            @Override
            protected Void doInBackground() throws Exception {
                super.doInBackground();
                runnable.run();
                return null;
            }
        };
        task.addPropertyChangeListener(INSTANCE);
        INSTANCE.task = task;
        frame.setVisible(true);
        task.execute();
        return task;
    }


    public static void compress(final List<File> files) {
        FileListCompressAction task = new FileListCompressAction(files);
        task.addPropertyChangeListener(INSTANCE);
        INSTANCE.task = task;
        frame.setVisible(true);
        task.execute();
    }

    private JProgressBar progressBar;

    private JZipActivitiesFrame() {
        super(new BorderLayout());

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        JPanel panel = new JPanel();
        panel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    }

    /**
     * Invoked when task's progress property changes.
     */
    public void propertyChange(final PropertyChangeEvent evt) {
        if ("progress".equals(evt.getPropertyName())) {
            int progress = (Integer) evt.getNewValue();
            if (progress == 100) {
                progressBar.setIndeterminate(true);
            } else {
                progressBar.setIndeterminate(false);
                progressBar.setValue(progress);
            }
        } else if ("state".equals(evt.getPropertyName())) {
            StateValue stateValue = (StateValue) evt.getNewValue();
            if (stateValue == StateValue.DONE) {
                try {
                    task.get();
                } catch (ExecutionException e) {
                    Throwable cause = e.getCause();
                    if (cause instanceof FileNotFoundException) {
                        FileNotFoundException fileNotFoundException = (FileNotFoundException) cause;
                        JOptionPane.showMessageDialog(null, "Unable to find '" + fileNotFoundException.getMessage() + "' file", "Compression impossible",
                                JOptionPane.ERROR_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(null, "Unable to unzip : " + cause.toString(), "Compression impossible", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    frame.setVisible(false);
                }
            }
        }
    }

    public static void toggleVisibility() {
        if (frame.isVisible()) {
            frame.setVisible(false);
        } else {
            frame.setVisible(true);
        }
    }

}
